package com.sgb.kjwl.view.ui.fragment.home;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLeaseSearchItemBinding;
import com.sgb.kjwl.di.machine.DaggerMachineFragComponent;
import com.sgb.kjwl.di.machine.MachineFragModule;
import com.sgb.kjwl.model.entity.LeaseSearchResultEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LeaseSearchEvent;
import com.sgb.kjwl.view.ui.adapter.home.LeaseSearchResultAdapter;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseSearchResultAskAdapter;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.home.LeaseSearchItemModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration2;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;


public class LeaseSearchItemFragment extends AppLazyFragment {
    @Inject
    LeaseSearchItemModel viewModel;
    private FragmentLeaseSearchItemBinding binding;
    private List<DictEntity3> sortDictEntityList;
    //    private TwoAreaPopWindow areaPopWindow;
    private List<String> cityList = new ArrayList<>();
    //    private List<ParentAreaEntity<List<ParentAreaEntity>>> areaEntityList;
    private List<DictEntity3> typeDictEntityList;
    private LeaseSearchResultAdapter adapter;//出租适配器
    private LeaseSearchResultAskAdapter askAdapter;//求租适配器
    private DictWindow5 classifyWindow;//分类
    private DictWindow5 sortWindow;//排序
    private String type = "";//租赁类型://1机械， 2 设备，3车辆，4 房产，5土地，6工厂 ，不限(空字符串)
    private String rentType = "1";//1=出租,2=求租
    private String keyword = "";//搜索条件
    //    private MultiLevelAreaPopWindow areaWindow;
    private ThreeLevelAreaWindow mAddressPop;
    //    private List<BaseAreaEntity<List<BaseAreaEntity>>> cityDatas = new ArrayList<>();
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;//省市区
    private String provinceName = "";
    private String cityName = "";

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMachineFragComponent.builder()
                .appComponent(appComponent)
                .machineFragModule(new MachineFragModule(this))
                .build()
                .inject(this);
    }

    public static LeaseSearchItemFragment newInstance(String type, String rentType, String keyword) {
        LeaseSearchItemFragment fragment = new LeaseSearchItemFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("rentType", rentType);
        bundle.putString("keyword", keyword);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null){
            type = getArguments().getString("type");
            rentType = getArguments().getString("rentType");
            keyword = getArguments().getString("keyword");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_lease_search_item, container, false);
        return binding.getRoot();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        checkDismiss(0);
    }

    @Override
    protected void onLazyLoad() {
        viewModel.filterJson.get().setType(type);
        viewModel.filterJson.get().setRentType(rentType);
        viewModel.filterJson.get().setKeyword(keyword);
        viewModel.filterJson.get().setProvinceNo(viewModel.getAreaCode());
        provinceName = viewModel.getAreaName();
        viewModel.filterJson.get().setSortWay("1");
        viewModel.getLeaseHomeSearch(false);
        viewModel.getCityData();
        if ("3".equals(type)) {
            binding.tvClassify.setText("品牌");
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initView() {
        initFilterView();
        binding.classifyLayout.setOnClickListener(this);
        binding.storeLayout.setOnClickListener(this);
        binding.sortLayout.setOnClickListener(this);

        if (adapter == null) {
            adapter = new LeaseSearchResultAdapter(getActivity(), null);
        }
        adapter.setOnItemClick(new AdapterOnItemClick<LeaseSearchResultEntity>() {
            @Override
            public void onItemClick(LeaseSearchResultEntity entity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5Url(entity.getDataId(), entity.getType());
                }
            }
        });

        if (askAdapter == null) {
            askAdapter = new LeaseSearchResultAskAdapter(getActivity(), null);
        }
        askAdapter.setOnItemClick(new AdapterOnItemClick<LeaseSearchResultEntity>() {
            @Override
            public void onItemClick(LeaseSearchResultEntity entity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getAskH5Url(entity.getDataId(), entity.getType());
                }
            }
        });

        if ("1".equals(rentType)) {
            binding.recyclerView.addItemDecoration(new RecyclerViewItemDecoration2(getResources().getDimension(R.dimen.dp10), getResources().getDimension(R.dimen.dp10)));
            binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
            binding.recyclerView.setAdapter(adapter);
        } else {
            binding.recyclerView.setAdapter(askAdapter);
            binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        }

        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getLeaseHomeSearch(false);
            }

            @Override
            public void onLoadMore() {
                viewModel.getLeaseHomeSearch(true);
            }
        });

    }

    private void initFilterView() {
        //分类选择
        classifyWindow = new DictWindow5(getActivity());
        classifyWindow.setFocusable(false);
        classifyWindow.setOutsideTouchable(false);
        classifyWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                viewModel.filterJson.get().setFirstCategoryNo(dictEntity.getId());
                viewModel.getLeaseHomeSearch(false);
            }
        });
        classifyWindow.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.classifyArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });

        //地区选择
//        areaPopWindow = new TwoAreaPopWindow(getActivity());
//        areaPopWindow.setFocusable(false);
//        areaPopWindow.setOutsideTouchable(false);
//        areaPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
//            @Override
//            public void result(Object key1, Object key2, Object key3) {
//                List<ParentAreaEntity> selectedEntities = (List<ParentAreaEntity>) key2;
//                cityList.clear();
//                if (selectedEntities != null) {
//                    for (ParentAreaEntity selected : selectedEntities) {
//                        cityList.add(selected.getNo());
//                    }
//                }
//                viewModel.filterJson.get().setCityNo((String) key1);
//                viewModel.filterJson.get().setAreaNos(cityList);
//                viewModel.getLeaseHomeSearch(false);
//            }
//        });
//        areaPopWindow.setOnCloseBack(new TwoAreaPopWindow.OnCloseBack() {
//            @Override
//            public void dismiss() {
//                binding.storeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
//            }
//        });

//        areaWindow = new MultiLevelAreaPopWindow(getActivity());
//        areaWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
//            @Override
//            public void result(Object key1, Object key2, Object key3) {
//                List<BaseAreaEntity> selectedEntities = (List<BaseAreaEntity>) key3;
//                cityList.clear();
//                if (selectedEntities != null) {
//                    for (BaseAreaEntity selected : selectedEntities) {
//                        if(!TextUtils.isEmpty(selected.getNo())){
//                            cityList.add(selected.getNo());
//                        }
//                    }
//                }
//                viewModel.filterJson.get().setCityNo(((BaseAreaEntity) key2).getNo());
//                viewModel.filterJson.get().setAreaNos(cityList);
//                viewModel.getLeaseHomeSearch(false);
//            }
//        });
//        areaWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                binding.storeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
//            }
//        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;
                viewModel.filterJson.get().setAreaNos(getCityList(listKey3)); //获取区多选列表
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    viewModel.filterJson.get().setCityNo(listKey2.get(0).getNo());
                } else {
                    viewModel.filterJson.get().setCityNo("");
                }
                viewModel.filterJson.get().setProvinceNo(listKey1.get(0).getNo());
                provinceName = listKey1.get(0).getName();
            } catch (Exception exception) {
            }
            viewModel.getLeaseHomeSearch(false);
//            if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
//                updateChooseTextStatus(binding.storeLayout, binding.tvArea, 2, cityName);
//            } else {
//                updateChooseTextStatus(binding.storeLayout, binding.tvArea, 2, provinceName);
//            }
        });
        mAddressPop.setOnDismissListener(() -> {
            binding.storeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
        });

        //排序选择
        sortWindow = new DictWindow5(getActivity());
        sortWindow.setFocusable(false);
        sortWindow.setOutsideTouchable(false);
        sortWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                viewModel.filterJson.get().setSortWay(dictEntity.getId());
                viewModel.getLeaseHomeSearch(false);
            }
        });
        sortWindow.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.sortArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });
    }

    public void showList(List<LeaseSearchResultEntity> list, boolean isLoadMore) {
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                if ("1".equals(rentType)) {
                    adapter.addDatas(list);
                } else {
                    askAdapter.addDatas(list);
                }
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }

            binding.recyclerView.refreshComplete();
            binding.recyclerView.setLoadingMoreEnabled(true);
            if ("1".equals(rentType)) {
                adapter.setDatas(list);
            } else {
                askAdapter.setDatas(list);
            }
        }
    }

    //设置一级分类数据
    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }

        classifyWindow.setData(data);
        classifyWindow.setCheckDefaultById(data.get(0).getId());
    }

    //设置排序数据
    public void showSortPopWindow(List<DictEntity3> data) {
        this.sortDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        sortWindow.setData(data);
        sortWindow.setCheckDefaultById(data.get(0).getId());
    }

//    public void showAddressDatas(List<BaseAreaEntity<List<BaseAreaEntity>>> datas) {
//        this.cityDatas = datas;
//        if (datas == null || datas.size() == 0) return;
//        BaseAreaEntity baseAreaEntity = new BaseAreaEntity();
//        baseAreaEntity.setName("不限");
//        baseAreaEntity.setNo("");
//        baseAreaEntity.setChildren(new ArrayList<>());
//        datas.add(0, baseAreaEntity);
//        for (int i = 0; i < datas.size(); i++) {
//            datas.get(i).getChildren().add(0, baseAreaEntity);
//        }
//        areaWindow.setCityList(datas);
//        areaWindow.setCitySelectType(true);
//        areaWindow.setAreaSelectType(true, false);
//    }

    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        if (data != null && data.size() > 0) {
            addressEntityList = data;
            viewModel.filterJson.get().setProvinceNo(provinceNo);
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }

    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
            case R.id.classify_layout://分类
                binding.classifyArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                classifyWindow.setCheckDefaultById(viewModel.filterJson.get().getFirstCategoryNo());
                classifyWindow.showPopwindow(binding.classifyLayout);
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel(type);
                }
                break;
            case R.id.store_layout://地区
                binding.storeArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                mAddressPop.showPopwindow(binding.storeLayout);
                if (addressEntityList == null) {
                    viewModel.getCityData();
                }
                break;
            case R.id.sort_layout://排序
                binding.sortArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                sortWindow.setCheckDefaultById(viewModel.filterJson.get().getSortWay());
                sortWindow.showPopwindow(binding.sortLayout);
                if (sortDictEntityList == null) {
                    viewModel.getFilterSort();
                }
                break;
        }
    }

    private void checkDismiss(int resId) {
        if (classifyWindow != null && classifyWindow.isShowing() && R.id.classify_layout != resId) {
            classifyWindow.dismiss();
        }
        if (mAddressPop != null && mAddressPop.isShowing() && R.id.store_layout != resId) {
            mAddressPop.dismiss();
        }
        if (sortWindow != null && sortWindow.isShowing() && R.id.sort_layout != resId) {
            sortWindow.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LeaseSearchEvent event) {//搜索
        if (event.getMessageTag() == EventConstant.EVENT_LEASE_SEARCH_FILTER) {
            keyword = (String) event.getMessageData();
            viewModel.filterJson.get().setKeyword(keyword);
            viewModel.getLeaseHomeSearch(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
